#include "gpt.h"

void gpt_delay_init(void)
{
    GPT1->CR |= (0x01 << 15);
    while((GPT1->CR >> 15) & 0x1);

    GPT1->CR |= 0x1 << 9;

    GPT1->CR &= ~(0x7 << 6);
    GPT1->CR |= (0x1 << 6);

    GPT1->PR = 65;
    GPT1->OCR[0] = 0xFFFFFFFF;

    GPT1->CR |= 1 << 0;
}

void delay_us(unsigned int us)
{
    unsigned int oldcnt, newcnt;
    oldcnt = GPT1->CNT;
    while(1)
    {
        newcnt = GPT1->CNT;
        if(newcnt > oldcnt && newcnt - oldcnt >= us)
        {
            break;
        }
        else if(newcnt < oldcnt && 0xFFFFFFFF - oldcnt + newcnt >= us)
        {
            break;
        }
    }
}

void delay_ms(unsigned int ms)
{
    int i = 0;
    for(i = 0; i < ms; i++)
    {
        delay_us(1000);
    }
}

void delay_s(unsigned int s)
{
    int i = 0;
    for(i = 0; i < s; i++)
    {
        delay_ms(1000);
    }
}